package utils

import (
	"fmt"
	"io/ioutil"
	"runtime"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"github.com/json-iterator/go"
)

var dbConfig = new(DataSource)

func ConnectMysql() *sqlx.DB {
	var cfg_path string
	if runtime.GOOS == "windows" {
		cfg_path = "conf/datasource.json"
	} else {
		cfg_path = "../etc/datasource.json"
	}

	b, err := ioutil.ReadFile(cfg_path)
	if err != nil {
		panic("DB config read err")
	}
	err = jsoniter.Unmarshal(b, dbConfig)
	if err != nil {
		panic(err)
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True",
		dbConfig.UserName, dbConfig.Passwd,
		dbConfig.Host, dbConfig.Port, dbConfig.DbName)
	Db, err := sqlx.Open("mysql", dsn)
	if err != nil {
		panic("mysql connect failed, " + err.Error())
	}
	return Db
}

// https://www.cnblogs.com/kaichenkai/p/11140555.html
func AddItem(Db *sqlx.DB, fileName string, filePath string) {
	_, err := Db.Exec("insert into td_location (file_name,file_path) values(?,?)", fileName, filePath)
	if err != nil {
		panic("data insert faied," + err.Error())
	}
}

type DataSource struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	UserName string `json:"user"`
	Passwd   string `json:"passwd"`
	DbName   string `json:"db"`
}
